<template>
  <div class="knowledge-base-management">
    <el-card class="knowledge-base-list-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <!-- 添加知识库按钮 -->
            <el-button type="primary" @click="showAddDialog = true">
              <el-icon>
                <Plus />
              </el-icon>
              添加知识库
            </el-button>
          </div>
          <div class="header-right">
            <!-- 搜索输入框 -->
            <el-input v-model="searchKeyword" placeholder="搜索知识库名称或描述" style="width: 250px; margin-right: 10px;"
              clearable @input="handleSearch" @clear="handleSearch">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
            <!-- 状态过滤下拉框 -->
            <el-select v-model="statusFilter" placeholder="所有状态" style="width: 120px; margin-right: 10px;" @change="handleStatusFilterChange">
              <el-option label="所有状态" value="" />
              <el-option label="公开" value="true" />
              <el-option label="私有" value="false" />
            </el-select>
            <!-- 重置按钮 -->
            <el-button @click="resetFilters" type="default">
              <el-icon>
                <Refresh />
              </el-icon>
              重置
            </el-button>
          </div>
        </div>
      </template>

      <!-- 知识库列表表格 -->
      <div class="table-wrapper">
        <el-table :data="getFilteredKnowledgeBases()" class="centered-table" v-loading="loading" element-loading-text="加载中..." empty-text="暂无数据" :row-key="(row) => row.knowledgeBaseId">
        <!-- 知识库名称列 -->
        <el-table-column prop="knowledgeBaseName" label="知识库名称" width="200" min-width="180">
          <template #default="{ row }">
            <div class="knowledge-base-name">
              <el-input v-if="editingRowId === row.knowledgeBaseId" v-model="row.knowledgeBaseName" placeholder="请输入知识库名称" size="small" />
              <el-tooltip v-else :content="row.knowledgeBaseName" placement="top">
                <span class="knowledge-base-name-text">{{ row.knowledgeBaseName }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <!-- 知识库描述列 -->
        <el-table-column prop="knowledgeBaseDescription" label="描述" min-width="300" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input v-if="editingRowId === row.knowledgeBaseId" v-model="row.knowledgeBaseDescription" size="small" />
            <span v-else>{{ row.knowledgeBaseDescription || '暂无描述' }}</span>
          </template>
        </el-table-column>
        <!-- 公开状态列 -->
        <el-table-column prop="isPublic" label="公开状态" width="120" align="center">
          <template #default="{ row }">
            <div v-if="editingRowId === row.knowledgeBaseId">
              <el-button 
                :type="row.isPublic ? 'success' : 'info'" 
                size="small"
                @click="togglePublicStatus(row)"
              >
                {{ row.isPublic ? '公开' : '私有' }}
              </el-button>
            </div>
            <el-tag v-else :type="row.isPublic ? 'success' : 'info'">
              {{ row.isPublic ? '公开' : '私有' }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 文档数量列 -->
        <el-table-column prop="documentCount" label="文档数量" width="100" align="center">
          <template #default="{ row }">
            <el-tag type="primary">{{ row.documentCount || 0 }}</el-tag>
          </template>
        </el-table-column>
        <!-- 创建时间列 -->
        <el-table-column prop="createdAt" label="创建时间" width="160" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
                   <!-- 操作列 -->
           <el-table-column label="操作" width="280" align="center">
          <template #default="{ row }">
            <div class="operation-buttons">
              <!-- 查看详情按钮 -->
              <el-button type="text" size="small" @click="viewKnowledgeBase(row)">
                <el-icon>
                  <View />
                </el-icon>
                查看
              </el-button>
              <!-- 管理文档按钮 -->
              <el-button type="text" size="small" @click="manageDocuments(row)">
                <el-icon>
                  <Document />
                </el-icon>
                文档
              </el-button>
              <div v-if="editingRowId === row.knowledgeBaseId">
                <!-- 保存编辑按钮 -->
                <el-button type="text" size="small" @click="saveEdit(row.knowledgeBaseId)" style="color: #67c23a;">
                  <el-icon>
                    <Check />
                  </el-icon>
                  保存
                </el-button>
                <!-- 取消编辑按钮 -->
                <el-button type="text" size="small" @click="cancelEdit" style="color: #f56c6c;">
                  <el-icon>
                    <Close />
                  </el-icon>
                  取消
                </el-button>
              </div>
              <div v-else>
                <!-- 开始编辑按钮 -->
                <el-button type="text" size="small" @click="openEdit(row.knowledgeBaseId)">
                  <el-icon>
                    <Edit />
                  </el-icon>
                  编辑
                </el-button>
                <!-- 删除按钮 -->
                <el-button type="text" size="small" @click="deleteKnowledgeBaseHandler(row)" style="color: #f56c6c;">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 添加知识库对话框 -->
    <el-dialog v-model="showAddDialog" title="添加知识库" width="500px">
      <el-form :model="knowledgeBaseForm" :rules="knowledgeBaseRules" ref="knowledgeBaseFormRef" label-width="100px">
        <el-form-item label="知识库名称" prop="knowledgeBaseName">
          <el-input v-model="knowledgeBaseForm.knowledgeBaseName" />
        </el-form-item>
        <el-form-item label="描述" prop="knowledgeBaseDescription">
          <el-input v-model="knowledgeBaseForm.knowledgeBaseDescription" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="公开状态" prop="isPublic">
          <el-switch v-model="knowledgeBaseForm.isPublic" active-text="公开" inactive-text="私有" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="addKnowledgeBaseHandler" :loading="addingKnowledgeBase">确定</el-button>
        </span>
      </template>
    </el-dialog>

         <!-- 知识库详情对话框 -->
     <el-dialog v-model="showDetailDialog" title="知识库详情" width="600px">
       <div class="knowledge-base-detail">
         <div class="detail-header">
           <h3>{{ selectedKnowledgeBaseDetail.knowledgeBaseName }}</h3>
           <div class="detail-meta">
             <span class="meta-item">
               <el-icon>
                 <Document />
               </el-icon>
               文档数量: {{ selectedKnowledgeBaseDetail.documentCount || 0 }}
             </span>
             <span class="meta-item">
               <el-icon>
                 <Message />
               </el-icon>
               {{ selectedKnowledgeBaseDetail.knowledgeBaseDescription || '暂无描述' }}
             </span>
           </div>
         </div>
         <el-divider />
         <div class="detail-content">
           <el-row :gutter="20">
             <el-col :span="12">
               <div class="detail-item">
                 <label>知识库ID:</label>
                 <span>{{ selectedKnowledgeBaseDetail.knowledgeBaseId }}</span>
               </div>
               <div class="detail-item">
                 <label>公开状态:</label>
                 <el-tag :type="selectedKnowledgeBaseDetail.isPublic ? 'success' : 'info'">
                   {{ selectedKnowledgeBaseDetail.isPublic ? '公开' : '私有' }}
                 </el-tag>
               </div>
             </el-col>
             <el-col :span="12">
               <div class="detail-item">
                 <label>创建时间:</label>
                 <span>{{ formatDate(selectedKnowledgeBaseDetail.createdAt) }}</span>
               </div>
               <div class="detail-item" v-if="selectedKnowledgeBaseDetail.updatedAt">
                 <label>更新时间:</label>
                 <span>{{ new Date(selectedKnowledgeBaseDetail.updatedAt) }}</span>
               </div>
             </el-col>
           </el-row>
         </div>
       </div>
     </el-dialog>

     <!-- 文档列表对话框 -->
     <el-dialog v-model="showDocumentsDialog" :title="`${selectedKnowledgeBase?.knowledgeBaseName || '知识库'} - 文档列表`" width="1000px">
       <div class="documents-container">
         <div class="documents-header">
           <div class="documents-info">
             <el-icon>
               <Document />
             </el-icon>
             <span>共 {{ documents.length }} 个文档</span>
           </div>
            <div class="documents-actions">
              <el-button type="primary" @click="openUploadDialog">
                <el-icon><Upload /></el-icon>
                上传文档
              </el-button>
              <el-button type="success" @click="openBatchUploadDialog">
                <el-icon><FolderAdd /></el-icon>
                批量上传
              </el-button>
            </div>
         </div>
         
         <el-table :data="documents" v-loading="documentsLoading" element-loading-text="加载中..." empty-text="暂无文档">
           <!-- 文档名称列 -->
           <el-table-column prop="documentTitle" label="文档名称" min-width="200" show-overflow-tooltip>
             <template #default="{ row }">
               <div class="document-title">
                 <el-icon class="document-icon">
                   <Document />
                 </el-icon>
                 <span>{{ row.documentTitle }}</span>
               </div>
             </template>
           </el-table-column>
           
           <!-- 文档类型列 -->
           <el-table-column prop="documentType" label="类型" min-width="80" align="center">
             <template #default="{ row }">
               <el-tag size="small" :type="getDocumentTypeTag(row.documentType)">
                 {{ row.documentType?.toUpperCase() || '未知' }}
               </el-tag>
             </template>
           </el-table-column>
           
           <!-- 文件大小列 -->
           <el-table-column prop="fileSize" label="大小" min-width="80" align="center">
             <template #default="{ row }">
               <el-tag type="info" size="small">{{ formatFileSize(row.documentFileSize) }}</el-tag>
             </template>
           </el-table-column>
           
           <!-- 访问级别列 -->
           <el-table-column prop="accessLevel" label="访问级别" min-width="80" align="center">
             <template #default="{ row }">
               <el-tag :type="row.accessLevel === 'public' ? 'success' : 'info'" size="small">
                 {{ row.accessLevel === 'public' ? '公开' : '私有' }}
               </el-tag>
             </template>
           </el-table-column>
           
           <!-- 上传时间列 -->
           <el-table-column prop="uploadTime" label="上传时间" min-width="120" align="center">
             <template #default="{ row }">
               {{ formatDate(row.createdAt) }}
             </template>
           </el-table-column>
           
           <!-- 操作列 -->
           <el-table-column label="操作" min-width="120" align="center">
             <template #default="{ row }">
               <div class="document-operations">
                 <el-button 
                   type="text" 
                   size="small" 
                   @click="downloadDocument(row)" 
                   :disabled="row.isDownloading"
                   :loading="row.isDownloading"
                   style="color: #409eff;">
                   <el-icon>
                     <Download />
                   </el-icon>
                   {{ row.isDownloading ? '下载中...' : '下载' }}
                 </el-button>
               </div>
             </template>
           </el-table-column>
         </el-table>
       </div>
     </el-dialog>

    <!-- 上传文档对话框 -->
    <el-dialog v-model="showUploadDialogInKB" title="上传文档" width="500px">
      <el-form :model="uploadFormInKB" label-width="100px">
        <el-form-item label="文档标题" required>
          <el-input v-model="uploadFormInKB.documentTitle" placeholder="请输入文档标题" />
        </el-form-item>
        <el-form-item label="知识库" required>
          <el-input v-model="uploadFormInKB.knowledgeBaseId" disabled />
        </el-form-item>
        <el-form-item label="选择文件" required>
          <el-upload :auto-upload="false" :limit="1" :show-file-list="true" :on-change="handleFileChangeInKB" :on-remove="handleFileRemoveInKB">
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">支持 txt, pdf, doc, docx 等格式文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showUploadDialogInKB = false">取消</el-button>
        <el-button type="primary" :loading="uploadingInKB" @click="handleUploadInKB">确定上传</el-button>
      </template>
    </el-dialog>

    <!-- 批量上传对话框 -->
    <el-dialog v-model="showBatchUploadDialogInKB" title="批量上传文档" width="600px">
      <el-form :model="batchUploadFormInKB" label-width="100px">
        <el-form-item label="知识库" required>
          <el-input v-model="batchUploadFormInKB.knowledgeBaseId" disabled />
        </el-form-item>
        <el-form-item label="访问级别" required>
          <el-radio-group v-model="batchUploadFormInKB.documentAccessLevel">
            <el-radio label="public">公开</el-radio>
            <el-radio label="private">私有</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择文件" required>
          <el-upload :auto-upload="false" :multiple="true" :show-file-list="true" :on-change="handleBatchFileChangeInKB" :on-remove="handleBatchFileRemoveInKB">
            <el-button type="primary">选择多个文件</el-button>
            <template #tip>
              <div class="el-upload__tip">可选择多个文件同时上传</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBatchUploadDialogInKB = false">取消</el-button>
        <el-button type="primary" :loading="batchUploadingInKB" @click="handleBatchUploadInKB">确定上传</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, View, Edit, Delete, Message, Document, Check, Close, Refresh, Download, Upload, FolderAdd
} from '@element-plus/icons-vue'
import {
  getKnowledgeBaseList,
  createKnowledgeBase,
  updateKnowledgeBase,
  deleteKnowledgeBase,
  getKnowledgeBaseDetail
} from '@/api/knowledgeBase'

import {
  getDocumentList ,
  uploadDocument,
  DownloadDocument,
  batchUploadDocuments
} from '@/api/document'

// ==================== 响应式数据定义 ====================
let DocumentRef=ref(null)
const loading = ref(false)
const addingKnowledgeBase = ref(false)
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const showDocumentsDialog = ref(false)
const editingRowId = ref(null)
let backupRow = null
const knowledgeBases = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')
const statusFilter = ref('')
const knowledgeBaseFormRef = ref(null)
const knowledgeBaseForm = ref({
  knowledgeBaseName: '',
  knowledgeBaseDescription: '',
  isPublic: false
})
const selectedKnowledgeBaseDetail = ref()
const selectedKnowledgeBase = ref(null)
const documents = ref([])
const documentsLoading = ref(false)
let searchTimer = null

// ================ 文档上传（单个/批量）对话框 ================
const showUploadDialogInKB = ref(false)
const uploadingInKB = ref(false)
const uploadFormInKB = ref({
  documentTitle: '',
  knowledgeBaseId: '',
  file: null
})

const showBatchUploadDialogInKB = ref(false)
const batchUploadingInKB = ref(false)
const batchUploadFormInKB = ref({
  knowledgeBaseId: '',
  documentAccessLevel: 'private',
  files: []
})

// ==================== 表单验证规则 ====================
const knowledgeBaseRules = {
  knowledgeBaseName: [
    { required: true, message: '请输入知识库名称', trigger: 'blur' },
    { min: 2, max: 50, message: '知识库名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  knowledgeBaseDescription: [
    { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
  ]
}

// ==================== 工具函数 ====================
// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes || bytes === 0) return '0 B'
  
  // 处理字符串类型的字节数
  if (typeof bytes === 'string') {
    bytes = parseInt(bytes, 10)
    if (isNaN(bytes)) return '未知'
  }
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  // 确保索引在有效范围内
  if (i < 0) return '0 B'
  if (i >= sizes.length) return '超大文件'
  
  const size = bytes / Math.pow(k, i)
  
  // 根据大小调整小数位数
  let precision = 2
  if (size >= 100) precision = 0
  else if (size >= 10) precision = 1
  
  return size.toFixed(precision) + ' ' + sizes[i]
}

const formatDate = (dateStr) => {
  if (!dateStr) return '未知时间'
  
  try {
    // 处理不同的日期格式
    let date
    if (typeof dateStr === 'string') {
      // 如果是ISO格式的字符串，直接创建Date对象
      if (dateStr.includes('T') || dateStr.includes('Z')) {
        date = new Date(dateStr)
      } else {
        // 处理其他格式的日期字符串
        date = new Date(dateStr.replace(/-/g, '/'))
      }
    } else if (dateStr instanceof Date) {
      date = dateStr
    } else {
      date = new Date(dateStr)
    }
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return '未知时间'
    }
    
    // 格式化为中文日期时间
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (e) {
    console.error('日期格式化错误:', e, '原始值:', dateStr)
    return '未知时间'
  }
}

// ==================== 数据加载函数 ====================
const loadKnowledgeBases = async () => {
  loading.value = true
  try {
    // 构建搜索参数
    const searchParams = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    // 添加搜索关键词
    if (searchKeyword.value) {
      searchParams.keyword = searchKeyword.value
    }
    
    // 添加状态过滤
    if (statusFilter.value !== '') {
      searchParams.isPublic = statusFilter.value
    }
    
    const res = await getKnowledgeBaseList(searchParams)
    
    if (res && res.data) {
      // 确保ID是字符串类型，避免类型不匹配问题
      knowledgeBases.value = res.data.map(item => ({
        ...item,
        id: String(item.knowledgeBaseId) // 强制转换为字符串
      }))
      total.value = res.total || knowledgeBases.value.length
    } else {
      knowledgeBases.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载知识库列表失败:', error)
    console.error('错误详情:', error.response?.data)
    
    // 如果API不可用，使用模拟数据
    if (error.response?.status === 404) {
      const mockData = [
        {
          id: '1',
          knowledgeBaseName: '技术文档库',
          knowledgeBaseDescription: '包含各种技术文档和手册',
          isPublic: true,
          documentCount: 15,
          createdAt: '2024-01-01T00:00:00Z',
          updatedAt: '2024-01-01T00:00:00Z'
        },
        {
          id: '2',
          knowledgeBaseName: '产品手册库',
          knowledgeBaseDescription: '产品使用手册和说明文档',
          isPublic: false,
          documentCount: 8,
          createdAt: '2024-01-02T00:00:00Z',
          updatedAt: '2024-01-02T00:00:00Z'
        }
      ]
      // 确保ID是字符串类型
      knowledgeBases.value = mockData.map(item => ({
        ...item,
        id: String(item.id)
      }))
      total.value = mockData.length
      ElMessage.warning('API暂时不可用，显示模拟数据')
    } else {
      knowledgeBases.value = []
      total.value = 0
      ElMessage.error('加载知识库列表失败')
    }
  }
  loading.value = false
}

// ==================== 搜索和过滤功能 ====================
const handleSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    // 搜索时重置编辑状态
    if (editingRowId.value !== null) {
      editingRowId.value = null
      backupRow = null
    }
    loadKnowledgeBases()
  }, 300)
}

const handleStatusFilterChange = () => {
  // 过滤时重置编辑状态
  if (editingRowId.value !== null) {
    editingRowId.value = null
    backupRow = null
  }
  loadKnowledgeBases()
}

const resetFilters = () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  // 重置时也重置编辑状态
  if (editingRowId.value !== null) {
    editingRowId.value = null
    backupRow = null
  }
  loadKnowledgeBases()
}

const getFilteredKnowledgeBases = () => {
  let filtered = knowledgeBases.value
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(kb => 
      (kb.knowledgeBaseName && kb.knowledgeBaseName.toLowerCase().includes(keyword)) ||
      (kb.knowledgeBaseDescription && kb.knowledgeBaseDescription.toLowerCase().includes(keyword))
    )
  }
  
  if (statusFilter.value !== '') {
    const isPublic = statusFilter.value === 'true'
    filtered = filtered.filter(kb => kb.isPublic === isPublic)
  }
  
  return filtered
}

// ==================== 事件处理函数 ====================
const openEdit = (id) => {
  // 确保只有一行处于编辑状态
  editingRowId.value = String(id) // 确保ID是字符串类型
  const row = knowledgeBases.value.find(item => String(item.id) === String(id))
  if (row) {
    backupRow = { ...row }
  }
}

const saveEdit = async (id) => {
  try {
    const row = knowledgeBases.value.find(item => item.id === id)
    if (!row) {
      ElMessage.error('未找到要保存的数据')
      return
    }
    console.log(row);
    
    const res = await updateKnowledgeBase(row.knowledgeBaseId,row)
    
    ElMessage.success('更新成功')
    editingRowId.value = null
    backupRow = null
    // 重新加载数据以确保数据一致性
    await loadKnowledgeBases()
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

const cancelEdit = () => {
  if (editingRowId.value !== null && backupRow) {
    const idx = knowledgeBases.value.findIndex(item => item.id === editingRowId.value)
    if (idx !== -1) {
      Object.assign(knowledgeBases.value[idx], backupRow)
    }
  }
  editingRowId.value = null
  backupRow = null
}

// 切换公开状态
const togglePublicStatus = (row) => {
  row.isPublic = !row.isPublic
}

const deleteKnowledgeBaseHandler = async (knowledgeBase) => {
  try {
    await ElMessageBox.confirm(
      `<div style="padding: 16px 0;">
        <div style="display: flex; align-items: center; margin-bottom: 16px;">
          <div style="width: 48px; height: 48px; border-radius: 50%; background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%); display: flex; align-items: center; justify-content: center; margin-right: 16px;">
            <i class="el-icon-warning" style="color: white; font-size: 24px;"></i>
          </div>
          <div>
            <h3 style="margin: 0 0 4px 0; color: #2c3e50; font-size: 18px; font-weight: 600;">删除知识库</h3>
            <p style="margin: 0; color: #7f8c8d; font-size: 14px;">此操作将永久删除该知识库及其所有关联数据</p>
          </div>
        </div>
        <div style="background: #fff5f5; border: 1px solid #fecaca; border-radius: 8px; padding: 12px; margin-bottom: 16px;">
          <p style="margin: 0; color: #dc2626; font-size: 14px; font-weight: 500;">
            <i class="el-icon-warning-outline" style="margin-right: 8px;"></i>
            即将删除知识库：<strong>"${knowledgeBase.knowledgeBaseName}"</strong>
          </p>
        </div>
        <div style="color: #6b7280; font-size: 13px; line-height: 1.5;">
          <p style="margin: 0 0 8px 0;">• 知识库中的所有文档将被永久删除</p>
          <p style="margin: 0 0 8px 0;">• 相关的向量数据将被清除</p>
          <p style="margin: 0;">• 此操作无法撤销，请谨慎操作</p>
        </div>
      </div>`, 
      '',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: '',
        dangerouslyUseHTMLString: true,
        customClass: 'custom-delete-dialog',
        confirmButtonClass: 'custom-confirm-button',
        cancelButtonClass: 'custom-cancel-button',
        center: false,
        roundButton: true,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            setTimeout(() => {
              done()
            }, 500)
          } else {
            done()
          }
        }
      }
    )
    
    const res = await deleteKnowledgeBase(knowledgeBase.id)
    
    ElMessage({
      message: '知识库删除成功',
      type: 'success',
      duration: 3000,
      showClose: true
    })
    loadKnowledgeBases()
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage({
        message: '删除失败，请稍后重试',
        type: 'error',
        duration: 3000,
        showClose: true
      })
    }
  }
}

const viewKnowledgeBase = async (knowledgeBase) => {
  try {
    const res = await getKnowledgeBaseDetail(knowledgeBase.knowledgeBaseId)
    selectedKnowledgeBaseDetail.value = res.data
    showDetailDialog.value = true
  } catch (e) {
    selectedKnowledgeBaseDetail.value = { ...knowledgeBase }
    showDetailDialog.value = true
  }
}

const manageDocuments = async (knowledgeBase) => {
  selectedKnowledgeBase.value = knowledgeBase
  showDocumentsDialog.value = true
  await loadDocuments(knowledgeBase.knowledgeBaseId)
}

// 加载文档列表
const loadDocuments = async (knowledgeBaseId) => {
  documentsLoading.value = true
  try {
    const res = await getDocumentList(knowledgeBaseId)
    console.log(res);
    
    if (res && res.data) {
      documents.value = res.data
    } else {
      documents.value = []
    }
  } catch (error) {
    console.error('加载文档列表失败:', error)
    // 如果API不可用，使用模拟数据
    if (error.response?.status === 404) {
      documents.value = [
        {
          id: '1',
          documentId: '1',
          documentTitle: '陈凯杰-简历',
          fileName: '陈凯杰-简历.pdf',
          documentType: 'pdf',
          fileSize: '2.5MB',
          uploadTime: '2024-01-01T10:00:00Z',
          accessLevel: 'private',
          documentAccessLevel: 'private'
        },
        {
          id: '2',
          documentId: '2',
          documentTitle: '技术规范文档.docx',
          fileName: '技术规范文档.docx',
          documentType: 'docx',
          fileSize: '1.8MB',
          uploadTime: '2024-01-02T14:30:00Z',
          accessLevel: 'private',
          documentAccessLevel: 'private'
        }
      ]
      ElMessage.warning('API暂时不可用，显示模拟数据')
    } else {
      documents.value = []
      ElMessage.error('加载文档列表失败')
    }
  }
  documentsLoading.value = false
}

// ================ 文档上传（单个/批量）事件 ================
const openUploadDialog = () => {
  if (!selectedKnowledgeBase.value) {
    ElMessage.warning('请先选择知识库')
    return
  }
  uploadFormInKB.value = {
    documentTitle: '',
    knowledgeBaseId: selectedKnowledgeBase.value.knowledgeBaseId,
    file: null
  }
  showUploadDialogInKB.value = true
}

const openBatchUploadDialog = () => {
  if (!selectedKnowledgeBase.value) {
    ElMessage.warning('请先选择知识库')
    return
  }
  batchUploadFormInKB.value = {
    knowledgeBaseId: selectedKnowledgeBase.value.knowledgeBaseId,
    documentAccessLevel: 'private',
    files: []
  }
  showBatchUploadDialogInKB.value = true
}

const handleFileChangeInKB = (file) => {
  uploadFormInKB.value.file = file.raw
  if (!uploadFormInKB.value.documentTitle) {
    const name = file.name || ''
    uploadFormInKB.value.documentTitle = name.includes('.') ? name.substring(0, name.lastIndexOf('.')) : name
  }
}

const handleFileRemoveInKB = () => {
  uploadFormInKB.value.file = null
}

const handleBatchFileChangeInKB = (file, fileList) => {
  batchUploadFormInKB.value.files = fileList.map(f => f.raw)
}

const handleBatchFileRemoveInKB = (file, fileList) => {
  batchUploadFormInKB.value.files = fileList.map(f => f.raw)
}

const handleUploadInKB = async () => {
  if (!uploadFormInKB.value.documentTitle || !uploadFormInKB.value.knowledgeBaseId || !uploadFormInKB.value.file) {
    ElMessage.warning('请填写完整信息')
    return
  }
  
  // 添加调试信息
  console.log('上传参数:', {
    documentTitle: uploadFormInKB.value.documentTitle,
    knowledgeBaseId: uploadFormInKB.value.knowledgeBaseId,
    fileName: uploadFormInKB.value.file.name,
    fileSize: uploadFormInKB.value.file.size
  })
  
  uploadingInKB.value = true
  try {
    await uploadDocument(uploadFormInKB.value)
    ElMessage.success('上传成功')
    showUploadDialogInKB.value = false
    if (selectedKnowledgeBase.value) {
      await loadDocuments(uploadFormInKB.value.knowledgeBaseId)
    }
  } catch (e) {
    console.error('上传失败详情:', e)
    ElMessage.error('上传失败')
  } finally {
    uploadingInKB.value = false
  }
}

const handleBatchUploadInKB = async () => {
  if (!batchUploadFormInKB.value.knowledgeBaseId || batchUploadFormInKB.value.files.length === 0) {
    ElMessage.warning('请选择知识库和文件')
    return
  }
  
  // 添加调试信息
  console.log('批量上传参数:', {
    knowledgeBaseId: batchUploadFormInKB.value.knowledgeBaseId,
    documentAccessLevel: batchUploadFormInKB.value.documentAccessLevel,
    fileCount: batchUploadFormInKB.value.files.length,
    fileNames: batchUploadFormInKB.value.files.map(f => f.name)
  })
  
  batchUploadingInKB.value = true
  try {
    await batchUploadDocuments(batchUploadFormInKB.value)
    ElMessage.success('批量上传成功')
    showBatchUploadDialogInKB.value = false
    if (selectedKnowledgeBase.value) {
      await loadDocuments(batchUploadFormInKB.value.knowledgeBaseId)
    }
  } catch (e) {
    console.error('批量上传失败详情:', e)
    ElMessage.error('批量上传失败')
  } finally {
    batchUploadingInKB.value = false
  }
}

// 获取文档类型标签样式
const getDocumentTypeTag = (type) => {
  const typeMap = {
    'pdf': 'danger',
    'doc': 'primary',
    'docx': 'primary',
    'txt': 'info',
    'md': 'warning',
    'html': 'success'
  }
  return typeMap[type?.toLowerCase()] || 'info'
}



// 查看文档
const viewDocument = (document) => {
  ElMessage.info(`查看文档: ${document.documentTitle}`)
  // 这里可以添加查看文档的逻辑，比如在新窗口打开或预览
}

// 下载文档
const downloadDocument = async (doc) => {
  // 防止重复点击
  if (doc.isDownloading) {
    return
  }
  
  try {
    // 设置下载状态
    doc.isDownloading = true
    
    let res = await DownloadDocument(doc.documentId)
    console.log(res.data);
    
    // 创建临时下载链接
    const url = window.URL.createObjectURL(res.data)
    const link = document.createElement('a')
    link.href = url
    link.download = doc.documentTitle || 'document'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success("下载成功")
    
    // 下载成功后自动关闭文档列表弹框
    setTimeout(() => {
      showDocumentsDialog.value = false
    }, 1000) // 延迟1秒关闭，让用户看到成功提示
    
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  } finally {
    // 重置下载状态
    doc.isDownloading = false
  }
}



const addKnowledgeBaseHandler = async () => {
  if (!knowledgeBaseForm.value) return
  addingKnowledgeBase.value = true
  
  try {
    const res = await createKnowledgeBase(knowledgeBaseForm.value)
    
    ElMessage.success('添加成功')
    loadKnowledgeBases()
    showAddDialog.value = false
    knowledgeBaseForm.value = {
      knowledgeBaseName: '',
      knowledgeBaseDescription: '',
      isPublic: false
    }
  } catch (error) {
    ElMessage.error('添加失败')
  } finally {
    addingKnowledgeBase.value = false
  }
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  // 分页改变时重置编辑状态
  if (editingRowId.value !== null) {
    editingRowId.value = null
    backupRow = null
  }
  loadKnowledgeBases()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  // 页码改变时重置编辑状态
  if (editingRowId.value !== null) {
    editingRowId.value = null
    backupRow = null
  }
  loadKnowledgeBases()
}

onMounted(() => {
  loadKnowledgeBases()
})

onUnmounted(() => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
})
</script>

<style scoped>
.knowledge-base-management {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
}

.knowledge-base-list-card {
  margin-bottom: 24px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
  width: 100%;
  max-width: 1400px;
  margin: 0 auto 24px auto;
  align-self: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid rgba(102, 126, 234, 0.1);
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
}

.header-left {
  display: flex;
  gap: 16px;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.knowledge-base-name {
  font-weight: 600;
  color: #2c3e50;
  font-size: 18px;
}

.knowledge-base-name-text {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.operation-buttons {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
  min-width: 100px;
}

.operation-buttons .el-button {
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.operation-buttons .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.operation-buttons .el-button .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  margin: 24px auto;
  width: 100%;
  max-width: 1400px;
  align-self: center;
}

.knowledge-base-detail {
  padding: 24px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.detail-header {
  margin-bottom: 24px;
  padding: 20px;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  border-radius: 12px;
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.detail-header h3 {
  margin: 0 0 12px 0;
  color: #2c3e50;
  font-size: 20px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.detail-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #7f8c8d;
  font-size: 14px;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 6px;
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.detail-content {
  margin-top: 24px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  border: 1px solid rgba(102, 126, 234, 0.1);
  transition: all 0.3s ease;
}

.detail-item:hover {
  background: rgba(102, 126, 234, 0.05);
  transform: translateX(4px);
}

.detail-item label {
  width: 120px;
  font-weight: 600;
  color: #2c3e50;
}

.detail-item span {
  color: #34495e;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #f0f2f5;
}

/* 表格样式 */
:deep(.el-table) {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  max-width: 100%;
}

:deep(.el-table th) {
  background: #f8fafc !important;
  color: #374151 !important;
  font-weight: 600;
  border: none;
  border-bottom: 2px solid #e5e7eb;
  padding: 16px 12px;
  font-size: 14px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f2f5;
  padding: 16px 12px;
  transition: all 0.3s ease;
}

:deep(.el-table tr:hover td) {
  background: #f9fafb;
  transform: none;
}

.documents-container {
  padding: 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  margin-top: 20px;
}

.documents-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 0 16px 0;
  border-bottom: 2px solid rgba(102, 126, 234, 0.1);
}

.documents-info {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.document-title {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  background: rgba(102, 126, 234, 0.05);
  border-radius: 6px;
  transition: all 0.3s ease;
}

.document-title:hover {
  background: rgba(102, 126, 234, 0.1);
  transform: translateX(4px);
}

.document-icon {
  color: #667eea;
  font-size: 18px;
}

.document-operations {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.document-operations .el-button {
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.document-operations .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 6px;
  font-weight: 500;
  padding: 4px 8px;
}

:deep(.el-tag--success) {
  background: linear-gradient(135deg, #00b894 0%, #00a085 100%);
  color: white;
  border: none;
}

:deep(.el-tag--warning) {
  background: linear-gradient(135deg, #fdcb6e 0%, #e17055 100%);
  color: white;
  border: none;
}

:deep(.el-tag--info) {
  background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
  color: white;
  border: none;
}

/* 自定义删除确认对话框样式 */
:deep(.custom-delete-dialog) {
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 25px 80px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

:deep(.custom-delete-dialog .el-message-box__header) {
  display: none;
}

:deep(.custom-delete-dialog .el-message-box__content) {
  padding: 32px 40px 24px 40px;
  text-align: left;
}

:deep(.custom-delete-dialog .el-message-box__btns) {
  padding: 0 40px 32px 40px;
  text-align: right;
  border-top: 1px solid #f0f2f5;
  margin-top: 24px;
  padding-top: 24px;
}

:deep(.custom-confirm-button) {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%) !important;
  border: none !important;
  border-radius: 12px !important;
  padding: 12px 24px !important;
  font-weight: 600 !important;
  font-size: 14px !important;
  box-shadow: 0 4px 16px rgba(255, 107, 107, 0.3) !important;
  transition: all 0.3s ease !important;
  margin-left: 12px !important;
}

:deep(.custom-confirm-button:hover) {
  transform: translateY(-2px) !important;
  box-shadow: 0 8px 25px rgba(255, 107, 107, 0.4) !important;
}

:deep(.custom-confirm-button:active) {
  transform: translateY(0) !important;
}

:deep(.custom-cancel-button) {
  background: #f8fafc !important;
  border: 1px solid #e2e8f0 !important;
  color: #64748b !important;
  border-radius: 12px !important;
  padding: 12px 24px !important;
  font-weight: 600 !important;
  font-size: 14px !important;
  transition: all 0.3s ease !important;
}

:deep(.custom-cancel-button:hover) {
  background: #e2e8f0 !important;
  border-color: #cbd5e1 !important;
  color: #475569 !important;
  transform: translateY(-1px) !important;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.knowledge-base-list-card,
.knowledge-base-detail,
.pagination-container,
:deep(.el-table) {
  animation: fadeInUp 0.6s ease-out;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .knowledge-base-management {
    padding: 16px;
    align-items: center;
  }
  
  .knowledge-base-list-card {
    max-width: 100%;
    margin: 0 auto 16px auto;
  }
  
  .table-wrapper {
    width: 100%;
    margin: 0 auto;
  }
  
  .centered-table {
    width: 100% !important;
    margin: 0 auto !important;
  }
  
  .pagination-container {
    max-width: 100%;
    margin: 16px auto;
  }
  
  .card-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .header-left,
  .header-right {
    width: 100%;
    justify-content: space-between;
  }
  
  .operation-buttons {
    gap: 4px;
    min-width: auto;
    flex-direction: column;
  }
  
  .operation-buttons .el-button {
    padding: 4px 8px;
    font-size: 11px;
    width: 100%;
  }
  
  .document-operations {
    gap: 4px;
    min-width: auto;
    flex-direction: column;
  }
  
  .document-operations .el-button {
    padding: 4px 8px;
    font-size: 11px;
    width: 100%;
  }
  
  /* 确保表格在小屏幕上可以水平滚动 */
  :deep(.el-table) {
    overflow-x: auto;
  }
  
  .document-operations .el-button {
    padding: 4px 8px;
    font-size: 11px;
  }
}

/* 确保表格完全居中的最终样式 */
.knowledge-base-management {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 24px;
  box-sizing: border-box;
}

/* 知识库列表卡片完全居中 */
.knowledge-base-list-card {
  width: 100%;
  max-width: 1400px;
  margin: 0 auto 24px auto;
  align-self: center;
}

/* 确保卡片内容区域全宽并居中 */
.knowledge-base-list-card .el-card__body {
  padding: 0;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 表格包装器完全居中 */
.table-wrapper {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
}

/* 专门的居中表格样式 */
.centered-table {
  width: 100% !important;
  max-width: 100% !important;
  margin: 0 auto !important;
  display: block !important;
}

/* 表格居中样式 */
:deep(.el-table) {
  width: 100% !important;
  max-width: 100% !important;
  margin: 0 auto !important;
  table-layout: fixed !important;
  display: block !important;
}

/* 表格内部包装器居中 */
:deep(.el-table__inner-wrapper) {
  width: 100% !important;
  margin: 0 auto !important;
}

:deep(.el-table__header-wrapper) {
  width: 100% !important;
  margin: 0 auto !important;
}

:deep(.el-table__body-wrapper) {
  width: 100% !important;
  margin: 0 auto !important;
}
</style>
